﻿namespace Compass.Maui.Services;
public interface IBaseService<TEntity> where TEntity : class
{
    Task<TEntity?> AddAsync(TEntity entity);
    Task<TEntity?> UpdateAsync(Guid id, TEntity entity);
    Task<TEntity?> DeleteAsync(Guid id);
    Task<TEntity?> GetFirstOrDefaultAsync(Guid id);
    Task<List<TEntity>> GetAllAsync();
}
public abstract class BaseService<TEntity> : IBaseService<TEntity> where TEntity : class
{
    private readonly IHttpRestClient _client;
    private readonly string _serviceName;
    protected BaseService(IHttpRestClient client,string serviceName)
    {
        _client = client;
        _serviceName = serviceName;
    }


    public async Task<TEntity?> AddAsync(TEntity entity)
    {
        var request = new BaseRequest
        {
            Method = Method.Post,
            Route = $"{_serviceName}/Add",
            Param = entity
        };
        //return await _client.ExecuteAsync<TEntity>(request);
        var response= await _client.ExecuteAsync<TEntity>(request);
        return response.Status? response.Result:null;
    }

    public async Task<TEntity?> UpdateAsync(Guid id, TEntity entity)
    {
        var request = new BaseRequest
        {
            Method = Method.Put,
            Route = $"{_serviceName}/{id}",
            Param = entity
        };
        var response = await _client.ExecuteAsync<TEntity>(request);
        return response.Status ? response.Result : null;
    }

    public async Task<TEntity?> DeleteAsync(Guid id)
    {
        var request = new BaseRequest
        {
            Method = Method.Delete,
            Route = $"{_serviceName}/{id}"
        };
        var response = await _client.ExecuteAsync<TEntity>(request);
        return response.Status ? response.Result : null;
    }

    public async Task<TEntity?> GetFirstOrDefaultAsync(Guid id)
    {
        var request = new BaseRequest
        {
            Method = Method.Get,
            Route = $"{_serviceName}/{id}"
        };
        var response = await _client.ExecuteAsync<TEntity>(request);
        return response.Status ? response.Result : null;
    }

    public async Task<List<TEntity>> GetAllAsync()
    {
        var request = new BaseRequest
        {
            Method = Method.Get,
            Route = $"{_serviceName}/All"
        };
        var response = await _client.ExecuteAsync<List<TEntity>>(request);
        return response.Status ? response.Result : new List<TEntity>();
    }
}